<script setup lang="ts">
import {isValidPrivate, mnemonicToPrivate, privateToPublic} from "@/common/lib/keyring";
import {encrypt, md5, sha256} from "@/common/util/crypto";
import {Wallet} from "@/types/wallet";
import {getKeyAccounts, lightKey} from "@/common/lib/remote";
import chain from "@/common/lib/chain";
import {eosChainId} from "@/common/util/network";
import {Address} from "ethereumjs-util";
import bs58 from "bs58";
import FrequencyModal from "@/entries/popup/setting/wallet/component/frequencyModal.vue";

type word={
  one: string;
  two:string,
  three:string,
  four:string,
  five:string,
  six:string,
  seven:string,
  eight:string,
  nine:string,
  ten:string,
  eleven:string,
  twelve:string
}
const words= ref({
  one:'',
  two:'',
  three:'',
  four:'',
  five:'',
  six:'',
  seven:'',
  eight:'',
  nine:'',
  ten:'',
  eleven:'',
  twelve:''
})
const isLoading = ref(false);
const showMessage = ref(false)
const checked = ref(false);
const accountList = ref([] as Wallet[]);
const { t } = useI18n();
const route = useRoute();
const isMnemonic = ref(false)
const chainId = ref(route.query.chainId ? (route.query.chainId as string) : eosChainId);
const viewFreModal = ref(false)
let timesNum: string | null= ''
const importAccounts:any = [];
let tipMessage = t('public.noAccountForPrivateKey');

//验证密码格式
const handleBlur = () =>{
  const rule = /^[A-Za-z]+$/
  let key: keyof word
  for (key in words.value){
    let ruleValue = rule.test(words.value[key])
    if( ruleValue == false){
      showMessage.value = true
      // console.log(1)
      return isMnemonic.value = true
    }else{
      showMessage.value =false
      // console.log(2)
    }
  }
}

//清空全部
const clearWords = () =>{
  words.value= {
    one:'',
    two:'',
    three:'',
    four:'',
    five:'',
    six:'',
    seven:'',
    eight:'',
    nine:'',
    ten:'',
    eleven:'',
    twelve:''
  }
}

//导入助记词
const handleImportMnemonic = async() =>{
  // const arr = ['one','two','three','four','five','six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve']
  const mnemonic:any = []
  let key: keyof word
  for (key in words.value){
    mnemonic.push(words.value[key])
  }
  let private_key = mnemonicToPrivate(mnemonic.join(' '))
  localStorage.setItem('mnemonic',mnemonic.join(' '))
  localStorage.setItem('privateKey',private_key)
  if (isLoading.value) return;
  isLoading.value = true;

  /** 判断协议勾选 */
  if (!checked.value) {
    isLoading.value = false;
    return window.msg.warning('请仔细阅读协议,并勾选');
  }

  /** 循环遍历需要取的协议 */

  let isKey = isValidPrivate(private_key);

  let ethAddress = '';

  if (!isKey && private_key.length == 64) {
    const privateKeyHex = Buffer.from(private_key, 'hex');

    ethAddress = Address.fromPrivateKey(privateKeyHex).toString();
    // alert("import key3 "+ethAddress);
    let versionedKey = '80' + private_key;
    const sha256dKey: any = sha256(Buffer.from(versionedKey, 'hex'));
    const checksum = sha256(Buffer.from(sha256dKey, 'hex'))
        .toString()
        .substring(0, 8);
    versionedKey += checksum;

    private_key = bs58.encode(new Uint8Array(Buffer.from(versionedKey, 'hex')));
    isKey = true;
  }
  if (isKey) {
    const network = useChainStore().networks.find((x) => x.chainId == chainId.value)!;
    const seed = sha256('metahub' + Math.random(), new Date().toString() as any)
        .toString()
        .substring(0, 16)
        .toUpperCase();
    const chainAccount: Wallet = {
      name: '',
      chainId: network.chainId,
      seed,
      blockchain: 'mos',  // eth, eth ...
      smoothMode: false,
      keys: [],
    };


    const publicKey = privateToPublic(private_key);

    const privateValue = encrypt(private_key, md5(chainAccount.seed + useUserStore().password));
    const key = { publicKey, privateKey: privateValue, permissions: [] };
    chainAccount.keys = [key];
    try {
      let accounts: string[] = [];
      try {
        accounts = await getKeyAccounts(network?.chain as lightKey, publicKey);

      } catch (_e) {}


      if (accounts.length == 0) {
        accounts = await chain.getApi(network?.chainId).getKeyAccounts(publicKey);
      }

      if (accounts.length == 0) {
        tipMessage = t('public.noAccountForPrivateKey');
      }
      for (let account of accounts) {
        const newAccount = Object.assign({}, chainAccount);
        newAccount.name = account; // real eos account
        // newAccount.address = ethAddress != '' ? ethAddress : account;

        let existed = false;
        for (let i = 0; i < useWalletStore().wallets.length; i++) {
          const element = useWalletStore().wallets[i];
          if (element.name === newAccount.name && element.chainId === newAccount.chainId) {
            existed = true;
            break;
          }
        }
        if (existed) {
          tipMessage = t('public.accountExists');
        } else {
          importAccounts.push(newAccount);
        }
      }

    } catch (e) {
      alert(e);
      console.log(e);
      window.msg.error(e);
      isLoading.value = false;
    }
  } else {
    tipMessage = t('public.invaildPrivateKey');
  }

  importAccounts.sort(sortAccounts);
  if (importAccounts.length > 1) {
    accountList.value = importAccounts;
    isShowChoose.value = true;
  } else if (importAccounts.length == 1) {
    await importWallet(importAccounts);
  } else {
    window.msg.error(tipMessage);
    isLoading.value = false;
  }
}
const importAccountList =()=>{
  viewFreModal.value = false
  isLoading.value = false;
  mnemonic.value = '';
  router.go(-1);
  window.msg.success(t('wallet.importSuccess'));
}
// import wallet
const router = useRouter();
const mnemonic = ref('');
const importWallet = async (wallets: Wallet[]) => {
  isLoading.value = true;
  timesNum = localStorage.getItem('mnemonicFrequency') !== null? localStorage.getItem('mnemonicFrequency') : '0'
  timesNum = (Number(timesNum) + 1).toString()
  localStorage.setItem('mnemonicFrequency',timesNum)

  const newWallets = [...useWalletStore().wallets, ...wallets].sort(sortAccounts);
  useWalletStore().setWallets(newWallets);

  // fetch permissions
  for (const wallet of wallets) {
    await chain.fetchPermissions(wallet.name, wallet.chainId);
  }

  const firstWallet = wallets[0];
  let index = useWalletStore().wallets.indexOf(firstWallet);
  useWalletStore().setSelectedIndex(index >= 0 ? index : 0);
  // useChainStore().setCurrentNetwork(networks[activeIndex.value]);
  viewFreModal.value = true



};
// select wallet
const isShowChoose = ref(false);
const handleSelectWallet = async (selectWallets: Wallet[]) => {
  if (selectWallets.length < 1) return window.msg.warning(t('wallet.selectOneAtLeast'));

  await importWallet(selectWallets);
};

// sort account
const sortAccounts = (first: any, second: any) => {
  if (first.chainId == second.chainId) {
    return first.name > second.name ? 1 : -1;
  } else {
    if (first.chainId == eosChainId) return -1;
    if (second.chainId == eosChainId) return 1;
    return first.chainId > second.chainId ? 1 : -1;
  }
};
</script>

<template>
  <div class="full-router">
    <div class="full-inner">
      <page-header :title="$t('public.importMnemonic')"></page-header>
      <div class="words_title">
        <img src="@/assets/images/daoruzhujici.svg" alt="">
        <span>{{$t('public.PleaseFillIn')}}</span>
      </div>
      <div class="words">
        <div class="words_input">
            <n-space vertical>
              <n-input
                  type="password"
                  show-password-on="click"
                  placeholder="Word#1"
                  :maxlength="8"
                  v-model:value="words.one"
                  @blur="handleBlur"
              />
              <n-input
                  type="password"
                  show-password-on="click"
                  placeholder="Word#2"
                  :maxlength="8"
                  v-model:value="words.two"
                  @blur="handleBlur"
              />
              <n-input
                  type="password"
                  show-password-on="click"
                  placeholder="Word#3"
                  :maxlength="8"
                  v-model:value="words.three"
                  @blur="handleBlur"
              />
              <n-input
                  type="password"
                  show-password-on="click"
                  placeholder="Word#4"
                  :maxlength="8"
                  v-model:value="words.four"
                  @blur="handleBlur"
              />
              <n-input
                  type="password"
                  show-password-on="click"
                  placeholder="Word#5"
                  :maxlength="8"
                  v-model:value="words.five"
                  @blur="handleBlur"
              />
              <n-input
                  type="password"
                  show-password-on="click"
                  placeholder="Word#6"
                  :maxlength="8"
                  v-model:value="words.six"
                  @blur="handleBlur"
              />
            </n-space>
        </div>
        <div class="words_input">
          <n-space vertical>
            <n-input
                type="password"
                show-password-on="click"
                placeholder="Word#7"
                :maxlength="8"
                v-model:value="words.seven"
                @blur="handleBlur"
            />
            <n-input
                type="password"
                show-password-on="click"
                placeholder="Word#8"
                :maxlength="8"
                v-model:value="words.eight"
                @blur="handleBlur"
            />
            <n-input
                type="password"
                show-password-on="click"
                placeholder="Word#9"
                :maxlength="8"
                v-model:value="words.nine"
                @blur="handleBlur"
            />
            <n-input
                type="password"
                show-password-on="click"
                placeholder="Word#10"
                :maxlength="8"
                v-model:value="words.ten"
                @blur="handleBlur"
            />
            <n-input
                type="password"
                show-password-on="click"
                placeholder="Word#11"
                :maxlength="8"
                v-model:value="words.eleven"
                @blur="handleBlur"
            />
            <n-input
                type="password"
                show-password-on="click"
                placeholder="Word#12"
                :maxlength="8"
                v-model:value="words.twelve"
                @blur="handleBlur"
            />
          </n-space>
        </div>
      </div>
      <div class="clear_words" @click="clearWords">
        {{$t('public.clearAll')}}
      </div>
      <div class="warningMessage" v-show="showMessage">
        <img src="@/assets/images/tishi.svg" alt="">
        <span>{{$t('public.WarningMessage')}}</span>
      </div>
      <div class="checkoutProtocol">
        <n-checkbox class="import-key-protocol" v-model:checked="checked"></n-checkbox>
        <span class="check-tip text-center cursor-pointer ml-[4px]" @click="checked = !checked">
        {{ $t('public.readAndAgree') }}
        <span @click="$router.push({ name: 'import-protocol' })" class="protocol-tip">
          {{ $t('public.readAndAgreeProtocols') }}
        </span>
      </span>
      </div>

      <n-button @click="handleImportMnemonic" :loading="isLoading" class="import-mnemonic-btn">
        {{ $t('public.importMnemonic') }}
      </n-button>
      <frequency-modal
          :is-show="viewFreModal"
          @close="viewFreModal = false"
          @submit="importAccountList"
      >
        <div>{{$t('setting.mnemonicFrequency')}}{{timesNum}}</div>
      </frequency-modal>
      <import-choose
          :is-show="isShowChoose"
          :accountList="accountList"
          @close="
                    isShowChoose = false;
                    isLoading = false;
                "
          @import="handleSelectWallet"
      ></import-choose>
    </div>
  </div>
</template>

<style scoped lang="scss">
.words_title{
  text-align: center;
  font-size: 20px;
  color: #000000;
  border-bottom: 1px solid #d9ecff ;
  padding: 10px;
  display: flex;
  align-items: center;

}
.words_title>span{
  display: inline-block;
  line-height: 30px;
  height: 30px;
  margin-left: 5px;
}
:deep(.n-input){
  background-color: #ecf5ff;
}
.words{
  width: 90%;
  margin: 15px auto;
  display: flex;
  justify-content: space-around;

  .words_input{
    width: 49%;
  }

}
.clear_words{
  text-align: center;
  font-size: 16px;
  color: #409eff;
  border-top: 1px solid #d9ecff;
  padding: 10px;
  font-weight: 700;
}
.warningMessage{
  width: 60%;
  margin: 0 auto;
  color: #f9f9f9;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid rgba(239, 179, 54, 0.02);
  border-radius: 8px;
  background-color: rgba(239,179,54,0.3);

  .warningMessage>span{
    line-height: 32px;
    height: 32px;
  }
}
.checkoutProtocol{
  width: 100%;
  text-align: center;
}
.import-key-protocol {
  margin-top: 8px;
  font-size: 14px;
  color: #999999;
  margin-right: 5px;
}
.import-mnemonic-btn {
  background: #409eff;
  box-shadow: 0px 2px 6px 0px rgba(210, 0, 244, 0.09);
  border-radius: 50px;
  width: 185px;
  height: 44px;
  margin: auto;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #ffffff;
  line-height: 20px;
  text-shadow: 0px 2px 6px rgba(210, 0, 244, 0.09);
  margin-top: 30px;
}
.import-mnemonic-btn:hover{
  background-color: #409eff;
  color: #ffffff;
  border: 0;
}
.import-mnemonic-btn:focus{
  background-color: #409eff;
  color: #ffffff;
}

.check-tip {
  color: #999999;
  font-size: 12px;
}
.protocol-tip {
  color: $color-primary;
  cursor: pointer;
}
</style>